-module(distserver1).
-export([start_storage_server/0,start_nano_server/1,nano_client_eval/1]).

start_nano_server(StorageNode) ->
    {ok, Listen} = gen_tcp:listen(5555, [binary, {packet, 2},
                                        {reuseaddr, true},
                                        {active, true}]),
    register(?MODULE,self()),
    spawn(fun() -> para_accept(Listen,StorageNode) end).

start_storage_server() -> 
    register( ?MODULE, spawn(fun() -> process_loop() end) ).

process_loop() ->
    receive
        {Pid,Str} ->
            Reply = handle_cmd(Str),
            Pid ! {Pid,Reply},
            process_loop()
    end.

para_accept(Listen,StorageNode) ->
    {ok, Socket} = gen_tcp:accept(Listen),
    Pid = spawn(fun() -> loop(Socket,StorageNode) end),
    gen_tcp:controlling_process(Socket,Pid),
    para_accept(Listen,StorageNode).

loop(Socket,StorageNode) ->
    receive
        {tcp, Socket, Bin} ->
            io:format("Server received binary = ~p~n" ,[Bin]),
            Str = binary_to_term(Bin),
            io:format("Server (unpacked) ~p~n" ,[Str]),
            Selfid = self(),
            {?MODULE , StorageNode} ! {Selfid,Str},
            receive
                {Selfid,Reply} ->
                    io:format("Server replying = ~p~n" ,[Reply]),
                    gen_tcp:send(Socket, term_to_binary(Reply))
            end,
            loop(Socket,StorageNode);
        {tcp_closed, Socket} ->
            io:format("Server socket closed~n" )
    end.

handle_cmd({set,Name,Value}) ->
    erlang:put(Name,Value),
    ok;

handle_cmd({get,Name}) ->
    case erlang:get(Name) of
        undefined ->
            {error,notfound};
        Value ->
            {ok,Value}
    end;

handle_cmd({delete,Name}) ->
    erlang:erase(Name),
    ok;

handle_cmd(Cmd) ->
    {error, Cmd}.


nano_client_eval(Str) ->
    {ok, Socket} =
        gen_tcp:connect("localhost" , 5555,
                         [binary, {packet, 2}]),
    ok = gen_tcp:send(Socket, term_to_binary(Str)),
    receive
        {tcp,Socket,Bin} ->
            io:format("Client received binary = ~p~n" ,[Bin]),
            Val = binary_to_term(Bin),
            io:format("Client result = ~p~n" ,[Val]),
            gen_tcp:close(Socket)
    end.